const PENDING = 'PENDING'
const FUFILLED = 'FUFILLED'
const REJECTED = 'REJECTED'

class mypromise {
	constructor(executor) {
		this.status = PENDING
		this.value = undefined
		this.reason = undefined
        this.onFullfilledCallbacks = []
        this.onRejectedCallbacks = []

		const resolve = (value) => {
			if (this.status === PENDING) {
				this.status = FUFILLED
				this.value = value
				// 发布
                this.onFullfilledCallbacks.forEach(fn => fn())
			}
		}
		const reject = (reason) => {
			if (this.status === PENDING) {
				this.status = REJECTED
				this.reason = reason
                this.onRejectedCallbacks.forEach(fn => fn())
			}
		}
		try {
			executor(resolve, reject)
		} catch (e) {
			reject(e)
		}
	}
	then(onFullfilled, onRejected) {
		if (this.status === FUFILLED) {
			onFullfilled(this.value)
		}

		if (this.status === REJECTED) {
			onRejected(this.reason)
		}

		if (this.status === PENDING) {
			// 订阅
			this.onFullfilledCallbacks.push(() => {
				onFullfilled(this.value)
			})
			this.onRejectedCallbacks.push(() => {
				onRejected(this.reason)
			})
		}
	}
}
module.exports = mypromise
